package com.ktg.mes.chanjet.task;

import cn.hutool.json.JSONObject;
import com.ktg.common.exception.BussinessException;
import com.ktg.mes.chanjet.content.InventoryClassContent;
import com.ktg.mes.chanjet.response.InventoryClassResponse;
import com.ktg.mes.chanjet.spi.ChanjetSpi;
import com.ktg.mes.wm.domain.WmMaterialStock;
import com.ktg.mes.wm.domain.WmWarehouse;
import com.ktg.mes.wm.service.IWmMaterialStockService;
import com.ktg.mes.wm.service.IWmWarehouseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * T+ 仓库存货同步
 */

@Slf4j
@Component("wareHouseSyncTask")
public class WareHouseSyncTask {

    @Autowired
    IWmWarehouseService service;
    @Autowired
    ChanjetSpi chanjetSpi;


    public void execute() {
        try {
            InventoryClassResponse response = chanjetSpi.getWareHouseList();
            List<WmWarehouse> warehouses = new ArrayList<>();
            List<Map> maps = response.getData();
            for (Map map : maps) {
                WmWarehouse warehouse = new WmWarehouse();
                warehouse.setWarehouseId(new BigDecimal((Double) map.get("ID")).longValue());
                warehouse.setWarehouseCode((String) map.get("Code"));
                warehouse.setWarehouseName((String) map.get("Name"));
                if (map.get("Admin.Name") != null) {
                    warehouse.setCharge((String) map.get("Admin.Name"));
                }
                warehouse.setRemark((String) map.get("Memo"));
                warehouse.setLocation((String) map.get("Address"));
                warehouse.setUpdateTime(new Date());
                warehouses.add(warehouse);
            }
            service.saveOrUpdateBatch(warehouses);
        } catch (Exception ex) {
            log.error("同步仓库库存 信息出错", ex);
            throw new BussinessException("执行失败");
        }
    }
}
